package com.jdd.fintech.morse.plugin.controller;

import com.alibaba.fastjson.JSONObject;
import com.jdd.fintech.morse.plugin.util.RequestParameterCus;
import com.jddglobal.filter.data.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @description: 请求控制层
 * @credit: 2022-04-13 14:20
 * @author: fengcheng
 **/

@RestController
@RequestMapping("/request")
public class RequestController {

    private static final Logger log = LoggerFactory.getLogger(RequestController.class);

    @ResponseBody
    @RequestMapping(value = "/openapi/encryptsAndDecrypts")
    public String encryptsAndDecrypts(@RequestBody JSONObject json, HttpServletRequest request) {
        System.out.println("RequestController.getRemoteAccessToken|请求已接收");
        AtomicReference<String> returnStr = new AtomicReference<>();
        try {
            Context context = RequestParameterCus.contextMorseEncrypts(json.toJSONString());
            String encryptsOrDecrypts = json.getString("encryptsOrDecrypts");
            if("remoteToken".equals(encryptsOrDecrypts)){
                log.info("开始进行测试远程获取Token功能！！！");
                RequestParameterCus.invokerRemoteToken().action(context, (r) -> {
                    String bodyStr = context.getRequest().getBody().toString();
                    log.info("返回加密后的数据结构，result: {}", bodyStr);
                    returnStr.set(bodyStr);
                });
            } else if("encrypts".equals(encryptsOrDecrypts)){
                log.info("开始进行测试加密功能！！！");
                RequestParameterCus.invokerEncrypts().action(context, (r) -> {
                    String bodyStr = context.getRequest().getBody().toString();
                    log.info("返回加密后的数据结构，result: {}", bodyStr);
                    returnStr.set(bodyStr);
                });
            }  else if("decrypts".equals(encryptsOrDecrypts)){
                log.info("开始进行测试解密功能！！！");
                RequestParameterCus.invokerDecrypts().action(context, (r) -> {
                    String bodyStr = context.getRequest().getBody().toString();
                    log.info("返回加密后的数据结构，result: {}", bodyStr);
                    returnStr.set(bodyStr);
                });
            }
            json.remove("encryptsOrDecrypts");
            log.info("测试加解密功能，处理完成！！！");
        } catch (Exception e) {
            log.error("测试加解密功能，发生异常，异常信息: {}", e.getMessage());
        }
        return returnStr.toString();
    }

}
